package com.guobox.movies.view.activity;

import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.guobox.movies.APP;
import com.guobox.movies.R;
import com.guobox.movies.constant.Constant;
import com.guobox.movies.entity.BgColors;
import com.guobox.movies.entity.MovieEntity;
import com.guobox.movies.nasManager.NasManager;
import com.guobox.movies.present.MovieDetailPresent;
import com.guobox.movies.present.MovieDetailPresentImp;
import com.guobox.movies.proxy.HttpUrls;
import com.guobox.movies.proxy.Proxy_Nas;
import com.guobox.movies.usecase.PlayMovieModel;
import com.guobox.movies.usecase.PlayMoviesModelImp;
import com.guobox.movies.utils.BgColorsUtils;
import com.guobox.movies.view.MovieDetailActivityIf;
import com.guobox.movies.view.adapter.StagePicsAdapter;
import com.guobox.movies.view.decoration.StageDecoration;
import com.guobox.movies.view.mview.BgView;
import com.guobox.movies.view.mview.PlayButton;
import com.guobox.movies.view.mview.RoundTextView;
import com.guobox.movies.view.mview.SpacingTextView;
import com.guobox.movies.view.mview.loadingProgress.LoadingDialog;



public class MovieDetailActivity extends Activity implements MovieDetailActivityIf,StagePicsAdapter.StageRvCallback {
    private static final String TAG = "MovieDetailActivity";
    TextView movieName, cateText, country, length, actors, actorName;
    RoundTextView blueray, triD, dts, level;
    ImageView posterImage, actorImage, movieScore;
    FrameLayout  wrapper_playbtn;
    ImageView bg_abstract, bg_actor;
    PlayButton playButtonUf, playButtonF;
    TextView movieDetail, movieActors;
    BgView bgView;
    RecyclerView recyclerView;
    BgColors bgColors;
    boolean keyLock = false;
    int keyCount = 0;
    MovieEntity movieEntity;
    MovieDetailPresent movieDetailPresent;
    LoadingDialog dialog;
    PlayMovieModel playMovieModel;
    private boolean isPlayLock = false;
    private NasManager nasManager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_movie_detail);
        nasManager = new NasManager(this);
//        NasEntity nasEntity = nasManager.getNas();
//        if (nasEntity == null || TextUtils.isEmpty(nasEntity.getNasIp())) {
//            Toast.makeText(this, "无法连接到主机", Toast.LENGTH_SHORT).show();
//            finish();
//        }
//        initData();
        initData();
    }

    private void initData() {
        movieDetailPresent = new MovieDetailPresentImp(this);
        playMovieModel = new PlayMoviesModelImp(this);
        Gson gson = new Gson();
        String movieItemJson = getIntent().getStringExtra(Constant.MOVIE_ITEM);
        if (!TextUtils.isEmpty(movieItemJson)) {
            movieEntity = gson.fromJson(movieItemJson, MovieEntity.class);
        } else {
            finish();
        }
        if (movieEntity.getMetadata() == null) {
            if (nasManager == null) {
                nasManager = new NasManager(this);
            }
            playMovie(movieEntity,nasManager.getNas().getNasIp());
            finish();
            return;
        }
        showLoadingProgress();
        movieDetailPresent.getMovieDetailRequest(movieEntity);
    }

    void initView() {
        bgView = (BgView) findViewById(R.id.wrapper_bg);
        bgView.setColos(bgColors);
        Typeface typeface = APP.getTypeface();


        posterImage = (ImageView) findViewById(R.id.iv_movie_poster1);
        movieName = (TextView) findViewById(R.id.tv_movie_name);
        movieName.setTypeface(typeface);
        movieName.setTextColor(bgColors.getMainTextColor());
        cateText = (TextView) findViewById(R.id.tv_movie_cate);
        cateText.setTypeface(typeface);
        cateText.setTextColor(bgColors.getSubTextColor());
        country = (TextView) findViewById(R.id.tv_movie_country);
        country.setTypeface(typeface);
        country.setTextColor(bgColors.getSubTextColor());
        length = (TextView) findViewById(R.id.tv_movie_time);
        length.setTypeface(typeface);
        length.setTextColor(bgColors.getSubTextColor());
        //pacingTextviewTest
        movieDetail = (TextView) findViewById(R.id.tv_movie_details);
        movieDetail.setTypeface(typeface);
        movieDetail.setTextColor(bgColors.getMainTextColor());
        movieActors = (TextView) findViewById(R.id.tv_movie_actor);
        movieActors.setTypeface(typeface);
        movieActors.setTextColor(bgColors.getMainTextColor());
        movieDetail.setLetterSpacing(SpacingTextView.LetterSpacing.NORMAL);
        actors = (TextView) findViewById(R.id.tv_actors);
        actors.setTypeface(typeface);
        actors.setTextColor(bgColors.getMainTextColor());
        movieScore = (ImageView) findViewById(R.id.iv_score);
        blueray = (RoundTextView) findViewById(R.id.rtv_bluray);
        blueray.setTypeface(typeface);
        blueray.setTextColor(bgColors.getSubTextColor());
        triD = (RoundTextView) findViewById(R.id.rtv_3d);
        triD.setTypeface(typeface);
        triD.setTextColor(bgColors.getSubTextColor());
        dts = (RoundTextView) findViewById(R.id.rtv_dts);
        dts.setTypeface(typeface);
        dts.setTextColor(bgColors.getSubTextColor());
        triD.setTextColor(bgColors.getSubTextColor());
        level = (RoundTextView) findViewById(R.id.rtv_pg);
        level.setTypeface(typeface);
        level.setTextColor(bgColors.getSubTextColor());
        playButtonUf = (PlayButton) findViewById(R.id.play_btn_uf);
        playButtonUf.setMainColor(bgColors.getSubTextColor());
        playButtonUf.setSubColor(Color.WHITE);
        playButtonF = (PlayButton) findViewById(R.id.play_btn_f);
        playButtonF.setMainColor(Color.WHITE);
        playButtonF.setSubColor(bgColors.getSubTextColor());

        //电影简介
        bg_abstract = (ImageView) findViewById(R.id.bg_abstract);
        bg_abstract.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    ObjectAnimator tobjectAnimator = ObjectAnimator.ofFloat(v, "alpha", 1f);
                    tobjectAnimator.setDuration(300);
                    tobjectAnimator.start();
                } else {
                    ObjectAnimator tobjectAnimator = ObjectAnimator.ofFloat(v, "alpha", 0f);
                    tobjectAnimator.setDuration(300);
                    tobjectAnimator.start();
                }

            }
        });
        bg_abstract.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MovieDetailActivity.this, TMovieReviewActivity.class);
                intent.setAction(Constant.REVIEW);
                intent.putExtra(Constant.COLORS, bgColors);
                intent.putExtra(Constant.REVIEW, movieEntity.getMetadata().getAbstracts());
                startActivity(intent);
            }
        });
        //演职员表
        bg_actor = (ImageView) findViewById(R.id.bg_actor);
        bg_actor.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    ObjectAnimator tobjectAnimator = ObjectAnimator.ofFloat(v, "alpha", 1f);
                    tobjectAnimator.setDuration(300);
                    tobjectAnimator.start();
                } else {
                    ObjectAnimator tobjectAnimator = ObjectAnimator.ofFloat(v, "alpha", 0f);
                    tobjectAnimator.setDuration(300);
                    tobjectAnimator.start();
                }
            }
        });
        bg_actor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MovieDetailActivity.this, TMovieReviewActivity.class);
                intent.setAction(Constant.ACTORS);
                intent.putExtra(Constant.COLORS, bgColors);
                intent.putExtra(Constant.DIRECTOR, movieEntity.getMetadata().getDirectors());
                intent.putExtra(Constant.WRITER, movieEntity.getMetadata().getWriters());
                intent.putExtra(Constant.ACTOR, movieEntity.getMetadata().getStars());
                startActivity(intent);
            }
        });
        //播放按钮
        wrapper_playbtn = (FrameLayout) findViewById(R.id.wrapper_playbtn);
        wrapper_playbtn.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    AnimationSet animationSet = new AnimationSet(true);
                    ScaleAnimation scaleAnimation = new ScaleAnimation(
                            1f,
                            1.12f,
                            1f,
                            1.12f,
                            Animation.RELATIVE_TO_SELF, 0.5f,
                            Animation.RELATIVE_TO_SELF, 0.5f
                    );
                    scaleAnimation.setDuration(400);
                    animationSet.addAnimation(scaleAnimation);
                    animationSet.setFillAfter(true);


                    ObjectAnimator focusAnimator = ObjectAnimator.ofFloat(playButtonF, "alpha", 1);
                    focusAnimator.setDuration(400);

                    ObjectAnimator unfocusAnimator = ObjectAnimator.ofFloat(playButtonUf, "alpha", 0);
                    unfocusAnimator.setDuration(400);
                    focusAnimator.start();
                    unfocusAnimator.start();
                    v.startAnimation(animationSet);
                } else {
                    AnimationSet animationSet = new AnimationSet(true);
                    ScaleAnimation scaleAnimation = new ScaleAnimation(
                            1.12f,
                            1f,
                            1.12f,
                            1f,
                            Animation.RELATIVE_TO_SELF, 0.5f,
                            Animation.RELATIVE_TO_SELF, 0.5f
                    );
                    scaleAnimation.setDuration(400);
                    animationSet.addAnimation(scaleAnimation);
                    animationSet.setFillAfter(true);

                    ObjectAnimator focusAnimator = ObjectAnimator.ofFloat(playButtonF, "alpha", 0);
                    focusAnimator.setDuration(400);

                    ObjectAnimator unfocusAnimator = ObjectAnimator.ofFloat(playButtonUf, "alpha", 1);
                    unfocusAnimator.setDuration(400);

                    focusAnimator.start();
                    unfocusAnimator.start();
                    v.startAnimation(animationSet);
                }
            }
        });
        wrapper_playbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // TODO: 2017/7/4 playMovie
                if (!isPlayLock) {
                    isPlayLock = true;
                    new Thread(){
                        @Override
                        public void run() {
                            try {
                                sleep(1500);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                                isPlayLock = false;
                            }
                            isPlayLock = false;
                        }
                    }.start();
                    playMovie(movieEntity,nasManager.getNas().getNasIp());
                }

            }
        });
        wrapper_playbtn.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                if (i == KeyEvent.KEYCODE_DPAD_LEFT) {
                    return true;
                } else if (i == KeyEvent.KEYCODE_DPAD_RIGHT) {
                    return true;
                }
                return false;
            }
        });
        View actorLayout = LayoutInflater.from(this).inflate(R.layout.item_actor, null);
        actorName = (TextView) actorLayout.findViewById(R.id.tv_actor);
        actorImage = (ImageView) actorLayout.findViewById(R.id.iv_actor);
        // TODO: 16/8/18
    }


    void setData(MovieEntity movieEntity) {
        if (movieEntity == null) {
            return;
        }

        movieName.setText(movieEntity.getMetadata().getMovieName() + " (" + movieEntity.getMetadata().getYear() + ")");
        if (movieEntity.getMetadata().getCategoryText() == null) {

            cateText.setText(R.string.movie_cate_no);
        }else {
            cateText.setText(movieEntity.getMetadata().getCategoryText().replace("/", " | "));
        }
        country.setText(movieEntity.getMetadata().getCountry().replace("|", " | "));
        length.setText(movieEntity.getMetadata().getLength() + " " + (movieEntity.getMetadata().getLengthtype() == null ? "" : movieEntity.getMetadata().getLengthtype()));
        if (!TextUtils.isEmpty(movieEntity.getMetadata().getLevel())) {
            level.setText(movieEntity.getMetadata().getLevel());
            level.setVisibility(View.VISIBLE);
        } else {
            level.setVisibility(View.GONE);
        }
        if (!TextUtils.isEmpty(movieEntity.getDimension())) {
            triD.setVisibility(View.VISIBLE);
            triD.setText(movieEntity.getDimension());
        } else {
            triD.setVisibility(View.GONE);
        }

        switch (movieEntity.getType()) {

            case Proxy_Nas.FILE:
                String fileName = movieEntity.getFiles().get(0).getName();
                String movieType = fileName.substring(fileName.lastIndexOf(".")+1, fileName.length());
                if (movieType.equals("iso")) {
                    blueray.setText(R.string.bluray);
                }else 
                blueray.setText(movieType);
                blueray.setVisibility(View.VISIBLE);
                break;
            case Proxy_Nas.SERIES:
                blueray.setText(R.string.series);
                blueray.setVisibility(View.VISIBLE);
                break;
            default:
                blueray.setVisibility(View.GONE);
        }
        
        try {
            Glide.with(this)
                    .load(getResources().getIdentifier("score_" + movieEntity.getMetadata().getDouban().replaceAll("\\.",""), "drawable", getPackageName()))
                    .centerCrop()
                    .into(movieScore);

        } catch (Exception e) {
            e.printStackTrace();
        }

        Log.i(TAG, HttpUrls.getMoviePosterURL(movieEntity.getMetadata().getMovieId(), HttpUrls.Pic_Middle)
                .build().toString());
        Glide.with(this)
                .load(HttpUrls.getMoviePosterURL(movieEntity.getMetadata().getMovieId(),HttpUrls.Pic_Middle)
                .build().toString())
                .override(540, 730)
                .centerCrop()
                .into(posterImage);
        movieDetail.setText(movieEntity.getMetadata().getAbstracts());
        StringBuilder actorsText = new StringBuilder();
        actorsText.append(getString(R.string.director));
        if (!TextUtils.isEmpty(movieEntity.getMetadata().getDirectors())) {
            actorsText.append(movieEntity.getMetadata().getDirectors());
        } else {
            actorsText.append(getString(R.string.nothing));
        }
        actorsText.append(getString(R.string.writer));
        if (!TextUtils.isEmpty(movieEntity.getMetadata().getWriters())) {
            actorsText.append(movieEntity.getMetadata().getWriters());
        } else {
            actorsText.append(getString(R.string.nothing));
        }
        actorsText.append(getString(R.string.actor));
        if (!TextUtils.isEmpty(movieEntity.getMetadata().getStars())) {
            actorsText.append(movieEntity.getMetadata().getStars());
        } else {
            actorsText.append(getString(R.string.nothing));
        }
        movieActors.setText(actorsText.toString());



        recyclerView = (RecyclerView) findViewById(R.id.rv_stage_pics);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        recyclerView.setAdapter(new StagePicsAdapter(this, movieEntity,this));
        recyclerView.addItemDecoration(new StageDecoration());

    }

    void showLoadingProgress() {
        dialog = new LoadingDialog(this, R.style.AlertDialogStyle, R.layout.view_tips_loading);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }
    void playMovie(MovieEntity movieEntity,String ip){
        if (movieEntity.getType().equals(Proxy_Nas.FILE)) {
            movieEntity.setHistory(new int[]{0});
            playMovieModel.playMovies(movieEntity,ip);
        } else if (movieEntity.getType().equals(Proxy_Nas.SERIES)) {
            playMovieModel.startFileListActivity(movieEntity,bgColors);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.isLongPress()) {
            keyLock = true;
        }
        if (keyLock) {
            keyCount = keyCount+1;
            if (keyCount > 10) {
                keyCount = 0;
                return false;
            }else {
                return true;
            }
        }
        return super.onKeyDown(keyCode,event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        keyLock = false;
        keyCount = 0;
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public void refreshDetail(MovieEntity movieEntity) {
        this.movieEntity = movieEntity;
        dialog.dismiss();
    }

    @Override
    public void refreshColors(String[] colors) {
        bgColors = BgColorsUtils.getBgColors(colors);
        initView();
        setData(movieEntity);
        if (bgView != null) {
            bgView.setVisibility(View.VISIBLE);
        }

        wrapper_playbtn.requestFocus();
    }

    @Override
    public void finish() {
        setResult(Constant.ResultLauncher);
        super.finish();
    }

    @Override
    public void onItemClick(int position) {
//        if (position != RecyclerView.NO_POSITION) {
//            Intent intent = new Intent(MovieDetailActivity.this,MovieStageActivity.class);
//            startActivity(intent);
//        }
    }
}
